package com.guigu.equipmentservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.R;
import com.guigu.equipmentservice.dto.DetectionReportDto;
import com.guigu.equipmentservice.entity.DetectionReport;
import com.guigu.equipmentservice.entity.DetectionReportImage;
import com.guigu.equipmentservice.entity.Equipment;
import com.guigu.equipmentservice.feign.MyDealFeign;
import com.guigu.equipmentservice.feign.MyOssFeign;
import com.guigu.equipmentservice.mapper.DetectionReportMapper;
import com.guigu.equipmentservice.service.DetectionReportImageService;
import com.guigu.equipmentservice.service.DetectionReportService;
import com.guigu.equipmentservice.service.EquipmentService;
import com.guigu.equipmentservice.vo.DetectionReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 检测报告表（存储设备检测的结果及结论） 服务实现类
 * </p>
 *
 * @author zcy
 * @since 2025-09-28
 */
@Service
public class DetectionReportServiceImpl extends ServiceImpl<DetectionReportMapper, DetectionReport> implements DetectionReportService {
    @Autowired
    private DetectionReportImageService detectionReportImageService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private DetectionReportMapper detectionReportMapper;

    @Autowired
    private MyDealFeign myDealFeign;

    @Autowired
    private MyOssFeign myOssFeign;

    @Override
    public R queryDetectionListByVo(Integer pageNum, Integer pageSize, DetectionReportVo vo) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<DetectionReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(vo.getBusinessmanId() != null, "businessman_id", vo.getBusinessmanId());
        queryWrapper.eq(vo.getAuditStatus() != null, "audit_status", vo.getAuditStatus());
        if (vo.getDetectionTime() != null && vo.getDetectionTime().size() >= 2) {
            queryWrapper.ge(vo.getDetectionTime().get(0) != null, "detection_time", vo.getDetectionTime().get(0));
            queryWrapper.le(vo.getDetectionTime().get(1) != null, "detection_time", vo.getDetectionTime().get(1));
        }
        List<DetectionReport> detectionReports = this.list(queryWrapper);

        for (DetectionReport d : detectionReports) {
            QueryWrapper<DetectionReportImage> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("report_id", d.getReportId());
            List<DetectionReportImage> detectionReportImages = detectionReportImageService.list(queryWrapper1);
            d.setDetectionReportImages(detectionReportImages);
            d.setEquipment((Equipment) equipmentService.selectEquipmentById(d.getEquipmentId()).getData().get("equipment"));
        }
        PageInfo<DetectionReport> pageInfo = new PageInfo<>(detectionReports);
        return R.ok().data("pageInfo", pageInfo);
    }

    @Override
    public R queryDetectionById(Long id) {
        DetectionReport detectionReport = this.getById(id);
        if (detectionReport != null) {
            QueryWrapper<DetectionReportImage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("report_id", detectionReport.getReportId());
            List<DetectionReportImage> detectionReportImages = detectionReportImageService.list(queryWrapper);
            detectionReport.setDetectionReportImages(detectionReportImages);
            detectionReport.setEquipment(equipmentService.getById(detectionReport.getEquipmentId()));
        }
        return R.ok().data("detectionReport", detectionReport);
    }

    @Override
    public R queryDetectionListByEquipmentId(Long equipmentId) {
        QueryWrapper<DetectionReport> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("equipment_id", equipmentId);
        DetectionReport detectionReport = this.getOne(queryWrapper1);
        if (detectionReport != null) {
            QueryWrapper<DetectionReportImage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("report_id", detectionReport.getReportId());
            List<DetectionReportImage> detectionReportImages = detectionReportImageService.list(queryWrapper);
            detectionReport.setDetectionReportImages(detectionReportImages);
            detectionReport.setEquipment(equipmentService.getById(detectionReport.getEquipmentId()));
        }
        return R.ok().data("detectionReport", detectionReport);
    }

    @Override
    public DetectionReport queryDetectionReportByEquipmentId(Long id) {
        QueryWrapper<DetectionReport> wrapper = new QueryWrapper<>();
        wrapper.eq("equipment_id", id);
        DetectionReport detectionReport = detectionReportMapper.selectOne(wrapper);
        return detectionReport;
    }

    @Override
    public R updateDetection(Long id, Integer status, String remark) {
        DetectionReport detectionReport = this.getById(id);
        if (detectionReport != null) {
            detectionReport.setAuditStatus(status);
            if (status == 1) {
                detectionReport.setAuditTime(LocalDateTime.now());
                Equipment equipment = equipmentService.getById(detectionReport.getEquipmentId());
                equipment.setIsDetected(1);
                equipment.setDetectionReportId(id);
                equipmentService.updateById(equipment);
            }
            detectionReport.setUpdateTime(LocalDateTime.now());
            detectionReport.setAuditTime(LocalDateTime.now());
            detectionReport.setAuditRemark(remark);
            this.updateById(detectionReport);
        }
        return R.ok();
    }


    // 检测报告图片保存
    @Override
    public R addDetectionReport(DetectionReportDto detectionReportDto) {
        // 2. 保存检测报告主表
        DetectionReport report = new DetectionReport();
        report.setEquipmentId(detectionReportDto.getEquipmentId());
        report.setBusinessmanId(detectionReportDto.getBusinessmanId());
        report.setDetectionTime(LocalDateTime.now());
        report.setAppearanceDetection(detectionReportDto.getAppearanceDetection());
        report.setComponentFunctionDetection(detectionReportDto.getComponentFunctionDetection());
        report.setPerformanceParameterDetection(detectionReportDto.getPerformanceParameterDetection());
        report.setDetectionConclusion(detectionReportDto.getDetectionConclusion());
        report.setAuditStatus(1);  // 默认为已审核
        report.setCreateTime(LocalDateTime.now());
        report.setUpdateTime(LocalDateTime.now());
        //保存主表，获取自增ID
        boolean saveReport = this.save(report);
        if (!saveReport) {
            throw new RuntimeException("检测报告主表保存失败");
        }
        //保存后自动获取检测表的ID
        Long reportId = report.getReportId();
        // 3. 处理图片上传（如果有图片）
        if (detectionReportDto.getImages() != null && !detectionReportDto.getImages().isEmpty()) {
            List<DetectionReportImage> imageList = new ArrayList<>();

            for (DetectionReportDto.ReportImageDto imageVo : detectionReportDto.getImages()) {
                // 3.1 校验图片参数
                if (imageVo.getFile() == null || imageVo.getFile().isEmpty()) {
                    throw new RuntimeException("图片文件不能为空");
                }
                if (imageVo.getSort() == null) {
                    throw new RuntimeException("图片排序号不能为空");
                }


                String imageUrl = imageVo.getFile();

                // 3.4 构建图片实体
                DetectionReportImage reportImage = new DetectionReportImage();
                reportImage.setReportId(Math.toIntExact(reportId));
                reportImage.setImageUrl(imageUrl);
                reportImage.setImageDesc(imageVo.getImageDesc());  // 允许为空
                reportImage.setSort(imageVo.getSort());
                reportImage.setCreateTime(LocalDateTime.now());
                imageList.add(reportImage);
            }

            // 3.5 批量保存图片信息到数据库
            boolean saveImages = detectionReportImageService.saveBatchImages(imageList);
            if (!saveImages) {
                throw new RuntimeException("检测报告图片保存失败");
            }
        }


        //并修改设备状态为已检测
        Equipment equipment = equipmentService.getById(detectionReportDto.getEquipmentId());
        equipment.setIsDetected(1);
        equipmentService.updateById(equipment);


        Boolean update = myDealFeign.update1(Math.toIntExact(equipment.getEquipmentId()));
        if (!update) {
            throw new RuntimeException("设备状态更新失败");
        }


        return R.ok().data("reportId", reportId).message("检测报告新增成功");
    }


}
